/**
 * Created by Administrator on 2017/12/1.
 */
$(function () {
    var ue = UE.getEditor('description', {initialFrameHeight: 300});
    layui.use('upload', function () {
        upload = layui.upload;
    });
    layui.use('form', function () {
        form = layui.form;
    });
    //初始化分类信息
    initCategory(allCategoryUrl);
    //获取品牌信息
    getBrandList(brandId);
    if (path) {
        //初始化已选择的分类
        initSelectProductCategory(path);
    }
    form.on('submit(productForm)', function (data) {
        product = {};
        var description = ue.getContent();
        var param = [];
        var paramDivs = $(data.form).find("div[name='param']");
        paramDivs.each(function (index, div) {
            var type = $(div).attr("type");
            var paramName = $(div).attr("paramName");
            var paramId = $(div).attr("paramId");
            if (typeof(paramId) == "undefined" || paramId == "undefined") {
                paramId = "";
            }
            var value;
            if (type == paramTypes.TEXT.key || type == paramTypes.SELECT_DATE.key || typeof(type) == "undefined" || type == "undefined") {
                var input = $(div).find("input");
                value = $(input).val();
            } else if (type == paramTypes.SELECT_ONE.key) {
                var inputs = $(div).find("input:checked");
                $(inputs).each(function (iIndex, input) {
                    value = $(input).val();
                });
            } else if (type == paramTypes.SELECT_MULTIPLE.key) {
                value = [];
                var inputs = $(div).find("input:checked");
                $(inputs).each(function (iIndex, input) {
                    value.push($(input).val());
                });
            }
            param.push({paramName: paramName, value: value, paramId: paramId});
        });
        product.param = param;
        product.description = description;
        product.brandId = data.field.brandId;
        product.name = data.field.name;
        product.productCategoryId = data.field.productCategoryId;
        var imageInputs = $("#productImage").find("input[name='image']");
        var images = [];
        imageInputs.each(function (index, input) {
            images.push($(input).val());
        });
        product.images = images;

        $("#productDiv").hide();
        $("#skuDiv").show();
        console.log(product);
        $step.toStep(2);
    });
    form.on('select(selectAttr)', function (data) {
        var option = $("option[value='" + data.value + "']");
        var keyId = $(option).attr("keyId");
        var button = $("button[keyId='" + keyId + "']");
        button.attr("valueId", data.value);
    });
    form.on('submit(skuForm)', function (data) {
        skus = [];
        attributeImage = [];
        attributes = [];
        if (hasAttributeFlag) {
            var skuLength = $("#skuTBody").find("tr").length;
            if (skuLength < 1) {
                layer.msg("至少设置一条sku信息！", {icon: 5});
                return false;
            }
            var trs = $("#skuTBody").find("tr");
            trs.each(function (index, tr) {
                var sku = {};
                var skuId = $(tr).attr("skuId");
                var skuName = $(tr).find("input[tdname='name']").val();
                var skuPrice = $(tr).find("input[tdname='price']").val();
                var skuCostPrice = $(tr).find("input[tdname='costPrice']").val();
                var skuMarketPrice = $(tr).find("input[tdname='marketPrice']").val();
                var skuWeight = $(tr).find("input[tdname='weight']").val();
                var skuInventory = $(tr).find("input[tdname='inventory']").val();
                var skuAttributes = $(tr).find("td[isattr='true']");
                sku.name = skuName;
                sku.price = skuPrice;
                sku.costPrice = skuCostPrice;
                sku.marketPrice = skuMarketPrice;
                sku.weight = skuWeight;
                sku.inventory = skuInventory;
                if (typeof(skuId) != "undefined" && skuId.length > 0) {
                    sku.id = skuId;
                }
                if (skuAttributes.length > 0) {
                    var attribute = [];
                    $(skuAttributes).each(function (sIndex, attr) {
                        var value = {};
                        value.attributeValue = $(attr).attr("value");
                        value.attributeKeyId = $(attr).attr("keyId");
                        value.attributeKey = $(attr).attr("keyName");
                        value.image = [];
                        var imagesInput = $("#skuImageTBody").find("tr[keyId='" + value.attributeKeyId + "'][value='" + value.attributeValue + "']").find("input[name='image']");
                        if (imagesInput.length < 1) {
                            value.hasImage = false;
                        } else {
                            value.hasImage = true;
                        }
                        imagesInput.each(function (iIndex, input) {
                            value.image.push($(input).val());
                        });
                        attribute.push(value);
                    });
                    sku.attribute = attribute;
                }
                skus.push(sku);
            });
            //sku图片
            var imageTrs = $("#skuImageTBody").find("tr");
            imageTrs.each(function (index, tr) {
                var imageObj = {};
                var keyId = $(tr).attr("keyId");
                var key = $(tr).attr("key");
                var value = $(tr).attr("value");
                imageObj.attributeKeyId = keyId;
                imageObj.attributeValue = value;
                imageObj.attribute_key = key;
                var images = [];
                var imagesInput = $(tr).find("input[name='image']");
                imagesInput.each(function (iIndex, input) {
                    images.push($(input).val());
                });
                imageObj.images = images;
                attributeImage.push(imageObj);
            });
        } else {
            skus.push(data.field);
        }
        $(".attrDiv").each(function (index, div) {
            var hasImage = $(div).attr("hasImage");
            var attributeKeyId = $(div).attr("keyId");
            var attributeKey = $(div).attr("keyName");
            var inputs = $(div).find("input");
            var values = [];
            if (hasImage === "true") {
                inputs.each(function (iIndex, input) {
                    var value = $(input).val();
                    $(attributeImage).each(function (attrIndex, attributeImg) {
                        if (attributeImg.attributeValue === value) {
                            values.push({value: value, images: attributeImg.images});
                        }
                    });
                });
            } else {
                inputs.each(function (iIndex, input) {
                    var value = $(input).val();
                    values.push({value: value});
                });
            }
            attributes.push({
                attributeKeyId: attributeKeyId,
                attributeKey: attributeKey,
                values: values,
                hasImage: hasImage
            });
        });
        doLast();
        layer.close(index);
    });
    upload.render({
        elem: '.productImage'
        , url: ueditorUrl + '/qiniu/oss/upload'
        /*  ,auto: false 不自动上传
         ,bindAction: '#'*/
        , before: function (obj) {
            var item = this.item;
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $(item).attr('src', result); //图片链接（base64）
                $(item).prev().css("visibility", "visible");
            });
        }
        , done: function (res) {
            var item = this.item;
            var input = $(item).nextAll("input[name='image']");
            input.val(res.data);
            //如果上传失败
            if (res.code < 1) {
                return layer.msg('上传失败');
            }
            //上传成功
        }
        , error: function () {
            return layer.msg('图片上传失败，请稍后再次上传或联系管理员');
        }
    });
    $step.step({
        index: 0,
        time: 500,
        title: ["选择商品分类", "填写商品详情", "填写sku详情", "发布商品"]
    });
});
var moneyReg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
var NonNegativeInteger = /^\d+$/;
var addParamFlag = false;
var hasAttributeFlag = false;
var product = {};
var skus = [];
var attributeImage = [];
var attributes = [];
var upload;
var subFlag = false;
var form;

//标签
var nameTd = '<td class="name"><input type="text" tdName="name"  lay-verify="required"></td>';
var priceTd = '<td class="price"><input type="text" tdName="price" onchange="changePrice(this)"  lay-verify="required"></td>';
var marketPriceTd = '<td class="price"><input type="text" tdName="marketPrice" onchange="changePrice(this)"  lay-verify="required"></td>';
var costPriceTd = '<td class="price"><input type="text" tdName="costPrice" onchange="changePrice(this)"  lay-verify="required"></td>';
var inventoryTd = '<td class="inventory"><input type="text" tdName="inventory" onchange="changeInventory(this)"  lay-verify="required"></td>';
var weightTd = '<td class="price"><input type="text" tdName="weight" onchange="changeWeight(this)"  lay-verify="required"></td>';

//选择好分类，进入商品信息
$("#makeProduct").click(function () {
    var releaseS = $(this).prop("disabled");
    if (nowCategoryId == productCategoryId || nowCategoryId == null || typeof(nowCategoryId) == "undefined") {
        if (releaseS == false) {//未被禁用
            nowCategoryId = productCategoryId;
            $("#categoryDiv").hide();
            $("#productDiv").show();
            $step.toStep(1);
        }
        getAttributeAndParam(productCategoryId, true, true);
        $("input[name='productCategoryId']").val(productCategoryId);
        $("input[name='productCategoryName']").val(productCategoryName);
        layer.close(index);
    } else {
        layer.confirm('如果改变分类将清空已填写的所有数据（包括sku），确定么？', {
            btn: ['确定', '取消'] //按钮
        }, function (index) {
            if (releaseS == false) {//未被禁用
                $("#categoryDiv").hide();
                $("#productDiv").show();
                $step.toStep(1);
                emptyAllAttribute();
            }
            getAttributeAndParam(productCategoryId, true, true);
            $("input[name='productCategoryId']").val(productCategoryId);
            $("input[name='productCategoryName']").val(productCategoryName);
            layer.close(index);
        }, function (index) {

        });
    }
});
//从sku返回到商品信息
function doProduct() {
    $("#skuDiv").hide();
    $("#productDiv").show();
    $step.toStep(1);
}
//从商品信息返回到分类
function doCategory() {
    $("#categoryDiv").show();
    $("#productDiv").hide();
    $step.toStep(0);
}
//添加参数
var addParamDiv = function (parentArea, param, num) {
    var type = param.type;
    var inputDiv;
    if (type == paramTypes.TEXT.key || typeof(type) == "undefined") {
        inputDiv = '<div class="layui-form-item" name="param" type="' + type + '" paramName="' + param.paramName + '" paramId="' + param.id + '"> ' +
            '<label class="layui-form-label">' + param.paramName + '</label> ' +
            '<div class="layui-input-inline add-width"> ' +
            '<input type="text" autocomplete="off" placeholder="请输入' + param.paramName + '" class="layui-input "> ' +
            '</div>' +
            '<div class="param-add-icon" onclick="deleteParam(this)"> ' +
            '<i class="layui-icon" style="font-size: 22px;">&#x1007;</i> ' +
            '</div>' +
            '</div>';
    } else if (type == paramTypes.SELECT_ONE.key) {
        var values = JSON.parse(param.param);
        inputDiv = '<div class="layui-form-item" name="param" type="' + type + '" paramName="' + param.paramName + '" paramId="' + param.id + '">' +
            '<label class="layui-form-label">' + param.paramName + '</label>' +
            '<div class="layui-input-inline add-width">';
        for (var i = 0; i < values.length; i++) {
            if (i == 0) {
                inputDiv += '<input type="radio" value="' + values[i] + '" title="' + values[i] + '" name="' + param.id + '" checked="checked">'
            } else {
                inputDiv += '<input type="radio" value="' + values[i] + '" title="' + values[i] + '" name="' + param.id + '">'
            }
        }
        inputDiv += '</div>' +
            '<div class="param-add-icon" onclick="deleteParam(this)"> ' +
            '<i class="layui-icon" style="font-size: 22px;">&#x1007;</i> ' +
            '</div>' +
            '</div>';
    } else if (type == paramTypes.SELECT_MULTIPLE.key) {
        var values = JSON.parse(param.param);
        inputDiv = '<div class="layui-form-item" name="param" type="' + type + '" paramName="' + param.paramName + '" paramId="' + param.id + '">' +
            '<label class="layui-form-label">' + param.paramName + '</label>' +
            '<div class="layui-input-inline add-width">';
        for (var i = 0; i < values.length; i++) {
            inputDiv += '<input type="checkbox" title="' + values[i] + '" value="' + values[i] + '">';
        }
        inputDiv += '</div>' +
            '<div class="param-add-icon" onclick="deleteParam(this)"> ' +
            '<i class="layui-icon" style="font-size: 22px;">&#x1007;</i> ' +
            '</div>' +
            '</div>';
    } else if (type == paramTypes.SELECT_DATE.key) {
        inputDiv = '<div class="layui-form-item" name="param" type="' + type + '" paramName="' + param.paramName + '" paramId="' + param.id + '"> ' +
            '<label class="layui-form-label">' + param.paramName + '</label> ' +
            '<div class="layui-input-inline add-width"> ' +
            '<input type="text" class="layui-input timeParam" placeholder="请选择' + param.paramName + '"> ' +
            '</div>' +
            '<div class="param-add-icon" onclick="deleteParam(this)"> ' +
            '<i class="layui-icon" style="font-size: 22px;">&#x1007;</i> ' +
            '</div>' +
            '</div>';
    }
    parentArea.append(inputDiv);
    form.render();
    layui.use('laydate', function () {
        var laydate = layui.laydate;
        //执行一个laydate实例
        laydate.render({
            elem: '.timeParam'//指定元素
        });
    });
}
//添加规格选项
var addAttributeDiv = function (parentArea, attribute) {
    var inputDiv;
    var key = attribute.key;
    var hasImage = key.hasImage;
    var valueList = attribute.valueList;
    inputDiv = '<div class="layui-form-item" >' +
        '<label class="layui-form-label">' + key.keyName + '</label>' +
        '<div class="layui-input-inline">' +
        '<select lay-search="" lay-filter="selectAttr">' +
        '<option value="">请选择' + key.keyName + '</option>';
    for (var i = 0; i < valueList.length; i++) {
        inputDiv += '<option value="' + valueList[i].id + '" valueName="' + valueList[i].valueName + '"' +
            ' keyId="' + key.id + '" keyName="' + key.keyName + '">' + valueList[i].valueName + '</option>';
    }
    inputDiv += '</select></div>';
    inputDiv += '<button class="layui-btn layui-btn-normal layui-btn-sm" ' +
        'type="button" keyId="' + key.id + '" onclick="addAttributeSelect(this,' + hasImage + ')">添加选项</button>';
    inputDiv += '<div keyId="' + key.id + '" keyName="' + key.keyName + '" class="attrDiv"  hasImage="' + hasImage + '"></div></div>';
    parentArea.append(inputDiv);
    form.render();
}
//获取商品规格和参数内容
function getAttributeAndParam(productCategoryId, paramFlag, attributeFlag) {
    //清空已有的数据
    $("#skuTBody").empty();
    $("#noAttributeSkuInfo").empty();
    nowCategoryId = productCategoryId;
    $.ajax({
        url: attributeAndParamUrl + "?productCategoryId=" + productCategoryId,
        type: "GET",
        dataType: "JSON",
        async: false,
        success: function (res) {
            attributeList = res.data.attributeList;
            paramList = res.data.paramList;
            var paramDiv = $("#paramDiv");
            var attributeDiv = $("#attributeDiv");
            var param = $("#params");
            var attribute = $("#attributes");
            if (paramFlag) {
                param.empty();
                if (paramList.length > 0) {
                    for (var i = 0; i < paramList.length; i++) {
                        addParamDiv(param, paramList[i], i);
                    }
                }
            }
            if (attributeFlag) {
                attribute.empty();
                if (attributeList.length > 0) {
                    hasAttributeFlag = true;
                    attributeDiv.show();
                    $("#noAttributeSkuInfo").hide();
                    for (var i = 0; i < attributeList.length; i++) {
                        addAttributeDiv(attribute, attributeList[i]);
                    }
                } else {
                    hasAttributeFlag = false;
                    addNoAttributeSku();
                    attributeDiv.hide();
                    $("#skuInfo").hide();
                    $("#noAttributeSkuInfo").show();
                }
            }
        }
    });
}
function getBrandList(brandId) {
    $.ajax({
        url: allBrandUrl,
        type: "GET",
        dataType: "JSON",
        async: false,
        success: function (res) {
            var brandList = res.data;
            if (brandId) {
                for (var i = 0; i < brandList.length; i++) {
                    if (brandId == brandList[i].id) {
                        $("#brandDiv").append("<option value='" + brandList[i].id + "' selected>" + brandList[i].name + "</option>")
                    } else {
                        $("#brandDiv").append("<option value='" + brandList[i].id + "'>" + brandList[i].name + "</option>")
                    }
                }
            } else {
                for (var i = 0; i < brandList.length; i++) {
                    $("#brandDiv").append("<option value='" + brandList[i].id + "'>" + brandList[i].name + "</option>")
                }
            }
            form.render('select');
        }
    });
}
//笛卡尔积算法
function cartesian(elements) {
    if (!Array.isArray(elements))
        throw new TypeError();
    var end = elements.length - 1,
        result = [];

    function addTo(curr, start) {
        var first = elements[start],
            last = (start === end);
        for (var i = 0; i < first.length; ++i) {
            var copy = curr.slice();
            copy.push(first[i]);
            if (last) {
                result.push(copy);
            } else {
                addTo(copy, start + 1);
            }
        }
    }

    if (elements.length)
        addTo([], 0);
    else
        result.push([]);
    return result;
}
function showAddParam() {
    if (addParamFlag) {
        $("#addParam").hide();
        addParamFlag = false;
    } else {
        $("#addParam").show();
        addParamFlag = true;

    }
}
function addParam() {
    var addParamName = $("#AddParamName").val();
    if (addParamName.replace(/(^s*)|(s*$)/g, "").length < 1) {
        layer.msg("参数名称不能为空！", {icon: 5});
    } else {
        var param = {};
        param.type = paramTypes.TEXT.key;
        param.paramName = addParamName;
        addParamDiv($("#params"), param);
        $("#AddParamName").val("");
    }

}
function deleteParam(paramIcon) {
    layer.confirm('确定删除该参数么？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        $(paramIcon).parent(".layui-form-item").remove();
        layer.msg('已删除', {icon: 1, time: 1000});
    }, function () {

    });
}
function addAttributeSelect(button, hasImage) {
    var valueId = $(button).attr("valueId");
    var keyId = $(button).attr("keyId");
    if (!valueId) {
        layer.msg("请选择规格！！", {icon: 5});
    } else {
        var div = $("div[keyId='" + keyId + "']");
        var option = $("option[value='" + valueId + "']");
        var valueName = option.attr("valueName");
        var keyName = option.attr("keyName");
        var inputs = div.find('input');
        var num = inputs.length;
        if (num > 0) {
            //判断是否有相同名称的规格
            var hasValueFlag = false;
            for (var i = 0; i < inputs.length; i++) {
                if (valueName == $(inputs[i]).val()) {
                    hasValueFlag = true;
                    break;
                }
            }
            if (hasValueFlag) {
                return;
            }
        }
        var addDiv = '<div class="layui-form-item" style="margin: 0;"> ' +
            '<label class="layui-form-label">规格选项</label> ' +
            '<div class="layui-input-inline">' +
            '<input type="text" autocomplete="off" class="layui-input" keyId="' + keyId + '" value="' + valueName + '"' +
            ' onchange="editAttr(this)">' +
            '</div>';
        addDiv += '<div class="param-add-icon" onclick="deleteAttr(this,' + hasImage + ')">' +
            '<i class="layui-icon" style="font-size: 22px;">&#x1007;</i> ' +
            '</div>' +
            '</div>';
        addSku({keyId: keyId, keyName: keyName, value: valueName}, hasImage);
        div.append(addDiv);
        sortTable();
    }
}
function emptyAllAttribute() {
    $("#skuImageTBody").empty();
    $("#skuImageDiv").hide();
    $("#skuTBody").empty();
    $("#skuInfo").hide();
}
function deleteAttr(attrIcon, hasImage) {
    var parent = $(attrIcon).parent(".layui-form-item");
    var input = $(parent.find("input"));
    var keyId = $(parent.parent(".attrDiv")).attr("keyId");
    var value = input.val();
    var tds = $("#skuTBody").find("td[value='" + value + "']");
    $(tds).each(function (index, td) {
        $(td).remove();
    });
    //获得当前删除规格的key下相同的td，如果没有，就删掉th.
    var hasAttrTd = $("#skuTBody").find("td[keyId='" + keyId + "']");
    if (hasAttrTd.length < 1) {
        var ths = $("#skuTHead").find("th[keyId='" + keyId + "']");
        $(ths).each(function (index, th) {
            $(th).remove();
        });
    }
    if (hasImage) {
        $("#skuImageTBody").find("tr[value='" + value + "']").remove();
        var length = $("#skuImageTBody").children().length;
        if (length < 1) {
            $("#skuImageDiv").hide();
        }
    }
    parent.remove();
    deleteSkuTr();
}
function deleteSkuTr() {
    //删除不该存在的sku
    var attrLength = 0;
    var attrDivs = $(".attrDiv");
    attrDivs.each(function (index, attrDiv) {
        var children = $(attrDiv).children();
        if (children.length > 0) {
            attrLength++;
        }
    });
    var trs = $("#skuTBody").find("tr");
    $(trs).each(function (index, tr) {
        var trTds = $(tr).find("td[isattr='true']");
        if (trTds.length < attrLength || trTds.length < 1) {
            $(tr).remove();
        }
    });
    var leftTr = $("#skuTBody").children();
    if (leftTr.length < 1) {
        $("#thParent").empty();
        $("#skuInfo").hide();
    }
}
function addSku(attribute, hasImage) {
    var attributeArray = [];
    //其他的规格div
    var otherAttrDiv = $(".attrDiv[keyId!='" + attribute.keyId + "']");
    //当前添加的规格div
    var addAttrDiv = $(".attrDiv[keyId='" + attribute.keyId + "']");
    //所有的规格div
    var allAttrDiv = $(".attrDiv");
    //其他的规格中已选择的input
    var otherAttrInputs = otherAttrDiv.find("input");
    //当前添加的规格中已选择的input
    var addAttrInputs = addAttrDiv.find("input");
    //当选中有图的规格时
    if (hasImage) {
        addSkuImageTr(attribute);
    }
    //当只添加当前这一种规格时
    if (otherAttrInputs.length < 1) {
        //只有一种规格就直接添加
        attributeArray.push([attribute]);
        createThead(cartesian(attributeArray));
        addSkuTr(attributeArray);
        return;
    }
    if (addAttrInputs.length < 1) {
        //当前添加的规格如果是第一个的话，给其他已添加的sku添加td和th
        addSkuTd(attribute);
    } else {
        //如果不是第一个，就添加新的sku
        for (var i = 0; i < allAttrDiv.length; i++) {
            var keyId = $(allAttrDiv[i]).attr("keyId");
            var keyName = $(allAttrDiv[i]).attr("keyName");
            if (keyId == attribute.keyId) {
                attributeArray.push([attribute]);
                continue;
            }
            var inputs = $(allAttrDiv[i]).find("input");
            if (inputs.length < 1) {
                continue;
            }
            var attributes = [];
            inputs.each(function (index, input) {
                var attr = {keyId: keyId, keyName: keyName, value: $(input).val()};
                attributes.push(attr);
            });
            attributeArray.push(attributes);
        }
        addSkuTr(attributeArray);
    }
}
//添加图片项
function addSkuImageTr(attribute) {
    var trs = $("#skuImageTBody").find("tr[value='" + attribute.value + "']");
    var imageNum = 5;
    var randomClass = generateRandomAlphaNum(11);
    if (trs.length > 0) {
        return;
    }
    var imageTr = '<tr value="' + attribute.value + '" keyId="' + attribute.keyId + '" key="' + attribute.keyName + '">' +
        '<td class="attribute-image-td">' + attribute.value + '</td>' +
        '<td>';
    for (var i = 0; i < imageNum; i++) {
        imageTr += '<div class="image-list">' +
            '<div class="sku-image-list">' +
            '<i class="layui-icon delete-sku-image" onclick="deleteImg(this)">&#x1007;</i>' +
            '<img src="' + basePath + '/resources/manage/image/noImg.png" class="' + randomClass + '">' +
            '<input type="hidden" name="image">' +
            '</div>';
        if (i == 0) {
            imageTr += '<p>主图</p>';
        } else {
            imageTr += '<p>细节图</p>';
        }
        imageTr += '</div>';
    }
    imageTr += '</td>' +
        '</tr>';
    $("#skuImageTBody").append(imageTr);
    $("#skuImageDiv").show();
    //todo 初始化uploder
    upload.render({
        elem: '.' + randomClass
        , url: ueditorUrl + '/qiniu/oss/upload'
        , before: function (obj) {
            var item = this.item;
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $(item).attr('src', result); //图片链接（base64）
                $(item).prev().css("visibility", "visible");
            });
        }
        , done: function (res) {
            var item = this.item;
            var input = $(item).nextAll("input[name='image']");
            input.val(res.data);
            //如果上传失败
            if (res.code < 1) {
                return layer.msg('上传失败');
            }
            //上传成功
        }
        , error: function () {
            return layer.msg('图片上传失败，请稍后再次上传或联系管理员');
        }
    });
}
//添加新的td
function addSkuTd(attribute) {
    addTh(attribute);
    var trs = $("#skuTBody").find("tr");
    var td = '<td class="attribute-td" isAttr="true"  keyName="' + attribute.keyName + '"  keyId="' + attribute.keyId + '" value="' + attribute.value + '" title="' + attribute.value + '">' + attribute.value + '</td>';
    trs.each(function (index, tr) {
        var last = $(tr).find("td[isAttr='true']:last");
        $(last).after(td);
    });
}
function addSkuTr(attributeArray) {
    var skuAttributeArray = cartesian(attributeArray);
    var ths = $("#skuTHead").find("th");
    var newAttributeArray = [];
    for (var i = 0, length = skuAttributeArray.length; i < length; i++) {
        var newAttribute = [];
        var attribute = skuAttributeArray[i];
        $(ths).each(function (index, th) {
            var keyId = $(th).attr("keyId");
            for (var j = 0; j < attribute.length; j++) {
                if (attribute[j].keyId == keyId) {
                    newAttribute.push(attribute[j]);
                }
            }
        });
        newAttributeArray.push(newAttribute);
    }
    var tBody = $("#skuTBody");
    //获取到了新增的sku
    for (var i = 0; i < newAttributeArray.length; i++) {
        var skuAttr = newAttributeArray[i];
        var tr = '<tr>';
        tr += nameTd;
        $(skuAttr).each(function (attrIndex, attribute) {
            tr += '<td class="attribute-td" isAttr="true" keyName="' + attribute.keyName + '" keyId="' + attribute.keyId + '" value="' + attribute.value + '" title="' + attribute.value + '">' + attribute.value + '</td>';
        });
        tr += priceTd + marketPriceTd + costPriceTd + inventoryTd + weightTd;
        tr += '</tr>';
        tBody.append(tr);
    }
    $("#skuInfo").show();
}
//添加无规格sku
function addNoAttributeSku() {
    var divs = '  <div class="div-info-title">' +
        '<p>sku信息</p> </div>' +
        ' <div class="layui-form-item"> ' +
        '<label class="layui-form-label">sku名称</label> ' +
        '<div class="layui-input-inline">' +
        ' <input type="text" name="name" lay-verify="required" autocomplete="off" placeholder="请输入sku名称"class="layui-input">' +
        ' </div>' +
        ' <div class="layui-form-mid layui-word-aux"></div> ' +
        '</div> ' +
        '<div class="layui-form-item"> ' +
        '<label class="layui-form-label">sku市场价</label> ' +
        '<div class="layui-input-inline"> ' +
        '<input type="text" name="marketPrice" onchange="changePrice(this)"  lay-verify="required" autocomplete="off" placeholder="请输入sku市场价"class="layui-input"> ' +
        '</div>' +
        ' <div class="layui-form-mid layui-word-aux">价格必须是0.01~999999999999.99之间的数字，此价格仅为市场参考售价，请根据该实际情况认真填写。</div> ' +
        '</div> <div class="layui-form-item"> ' +
        '<label class="layui-form-label">sku销售价</label> ' +
        '<div class="layui-input-inline">' +
        ' <input type="text" name="price" onchange="changePrice(this)"  lay-verify="required" autocomplete="off" placeholder="请输入sku销售价"class="layui-input">' +
        ' </div>' +
        ' <div class="layui-form-mid layui-word-aux">价格必须是0.01~999999999999.99之间的数字，且不能高于市场价。</div> ' +
        '</div>' +
        ' <div class="layui-form-item"> ' +
        '<label class="layui-form-label">sku成本价</label> ' +
        '<div class="layui-input-inline"> ' +
        '<input type="text" name="costPrice" onchange="changePrice(this)" lay-verify="required" autocomplete="off" placeholder="请输入sku成本价"class="layui-input">' +
        ' </div>' +
        '<div class="layui-form-mid layui-word-aux">价格必须是0.00~999999999999.99之间的数字，此价格为商户对所销售的商品实际成本价格进行备注记录，非必填选项</div>' +
        ' </div>' +
        ' <div class="layui-form-item">' +
        ' <label class="layui-form-label">sku库存</label> ' +
        '<div class="layui-input-inline">' +
        ' <input type="text" name="inventory" onchange="changeInventory(this)"  lay-verify="required" autocomplete="off" placeholder="请输入sku库存"class="layui-input">' +
        ' </div> ' +
        '<div class="layui-form-mid layui-word-aux">商铺库存数量必须为1~9999999999之间的整数</div> ' +
        '</div> <div class="layui-form-item"> ' +
        '<label class="layui-form-label">sku重量</label>' +
        ' <div class="layui-input-inline"> ' +
        '<input type="text" name="weight" onchange="changePrice(this)"  lay-verify="required" autocomplete="off" placeholder="请输入sku重量"class="layui-input"> ' +
        '</div> <div class="layui-form-mid layui-word-aux">重量数量必须为0.01~9999999999.99之间的数值</div> ' +
        '</div>'
    $("#noAttributeSkuInfo").append(divs);
}
//表格排序
function sortTable() {
    var tBody = $("#skuTBody");
    var allAttrDiv = $(".attrDiv");
    allAttrDiv.each(function (index, attrDiv) {
        var inputs = $(attrDiv).find("input");
        if (inputs.length > 0) {
            for (var i = 0; i < inputs.length; i++) {
                var value = $(inputs[i]).val();
                var tds = tBody.find("td[value='" + value + "']");
                for (var j = 0; j < tds.length; j++) {
                    //将同类型的tr放在当前tr的下面
                    if (j + 1 < tds.length) {
                        var tr = $(tds[j]).parent("tr");
                        // $(tds[j + 1]).hide();
                        // $(tds[j]).attr("rowspan",tds.length);
                        var nextTr = $(tds[j + 1]).parent("tr");
                        $(tr).after(nextTr);
                    }
                }
            }
            return false;
        }
    });
    /*  var trs = tBody.find("tr");
     trs.each(function (index, tr) {
     var firstTd = $(tr).find("td")[0];
     var firstVal = $(firstTd).html();
     trs.each(function(index1,tr1){
     if(index == index1){
     return true;
     }
     var nowTd = $(tr1).find("td")[0];
     var nowVal = $(nowTd).html();
     if(nowVal == firstVal){
     $(tr).after($(tr1));
     }
     });
     });*/
}
//创建tHead
function createThead(attributeArray) {
    var nameTh = '<th thName="name">' +
        '<div id="editName">名称<i class="layui-icon edit-icon" onclick="showBatch(\'Name\',true)">&#xe642;</i></div>' +
        '<div id="editTdName" hidden><input id="editTdNameInput" onblur="showBatch(\'Name\',false)" onchange="batchEdit(\'name\',this,1)"></div>' +
        '</th>';
    var priceTh = '<th thName="price">' +
        '<div id="editPrice">售价<i class="layui-icon edit-icon"  onclick="showBatch(\'Price\',true)">&#xe642;</i></div>' +
        '<div id="editTdPrice" hidden class="price"><input id="editTdPriceInput" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" onblur="showBatch(\'Price\',false)" onchange="batchEdit(\'price\',this,2)"></div>' +
        '</th>';
    var marketPriceTh = '<th thName="marketPrice">' +
        '<div id="editMarketPrice">市场价<i class="layui-icon edit-icon"  onclick="showBatch(\'MarketPrice\',true)">&#xe642;</i></div>' +
        '<div id="editTdMarketPrice" hidden class="price"><input id="editTdMarketPriceInput" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" onblur="showBatch(\'MarketPrice\',false)" onchange="batchEdit(\'marketPrice\',this,2)"></div>' +
        '</th>';
    var costPriceTh = '<th thName="costPrice">' +
        '<div id="editCostPrice">成本价<i class="layui-icon edit-icon"  onclick="showBatch(\'CostPrice\',true)">&#xe642;</i></div>' +
        '<div id="editTdCostPrice" hidden class="price"><input id="editTdCostPriceInput" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" onblur="showBatch(\'CostPrice\',false)" onchange="batchEdit(\'costPrice\',this,2)"></div>' +
        '</th>';
    var inventoryTh = '<th thName="inventory">' +
        '<div id="editInventory">库存<i class="layui-icon edit-icon"  onclick="showBatch(\'Inventory\',true)">&#xe642;</i></div>' +
        '<div id="editTdInventory" hidden class="inventory"><input id="editTdInventoryInput" onblur="showBatch(\'Inventory\',false)" onchange="batchEdit(\'inventory\',this,3)"></div>' +
        '</th>';
    var weightTh = '<th thName="weight">' +
        '<div id="editWeight">重量<i class="layui-icon edit-icon"  onclick="showBatch(\'Weight\',true)">&#xe642;</i></div>' +
        '<div id="editTdWeight" hidden class="price"><input id="editTdWeightInput" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" onblur="showBatch(\'Weight\',false)" onchange="batchEdit(\'weight\',this,4)"></div>' +
        '</th>';
    $("#thParent").empty();
    if (attributeArray.length < 1) {
        return;
    }
    $("#thParent").append(nameTh);
    $(attributeArray[0]).each(function (index, attr) {
        var th = '<th  keyId="' + attr.keyId + '" isAttr="true">' + attr.keyName + '</th>';
        $("#thParent").append(th);
    });
    $("#thParent").append(priceTh);
    $("#thParent").append(marketPriceTh);
    $("#thParent").append(costPriceTh);
    $("#thParent").append(inventoryTh);
    $("#thParent").append(weightTh);
}
//添加表格th
function addTh(attribute) {
    var th = '<th keyId="' + attribute.keyId + '" isAttr="true">' + attribute.keyName + '</th>';
    var lastTh = $("#thParent").find("th[isAttr='true']:last");
    $(lastTh).after(th);
}
//修改属性值
function editAttr(input) {
    var val = $(input).val();
    var value = $(input).attr("value");
    var keyId = $(input).attr("keyId");
    var tds = $("td[value='" + value + "'][keyId='" + keyId + "']");
    var allTds = $("#skuTBody").find("td[isattr='true']");
    //先判断是否重复
    for (var i = 0; i < allTds.length; i++) {
        var tdValue = $(allTds[i]).attr("value");
        if (tdValue === val) {
            // $(allTds[i]).val(value);
            $(input).val(value);
            layer.msg("规格名不可以重复！", {icon: 5, time: 1000});
            return;
        }
    }
    tds.each(function (index, td) {
        $(td).html(val);
        $(td).attr("value", val);
        $(td).attr("title", val);
    });

    var imageTr = $("#skuImageTBody").find("tr[value='" + value + "']");
    imageTr.attr("value", val);
    $(imageTr.find("td")[0]).html(val);
    $(input).attr("value", val);
}
//表格批量修改
function batchEdit(tdName, input, num) {
    var val = $(input).val();
    if (num == 2) {
        if (!moneyReg.test(val)) {
            $(input).val("");
            layer.msg("请输入正确的金额！", {icon: 5, time: 1000});
            return;
        }
    } else if (num == 3) {
        if (!NonNegativeInteger.test(val)) {
            $(input).val("");
            layer.msg("请输入正确的库存！", {icon: 5, time: 1000});
            return;
        }
    } else if (num === 4) {
        if (!moneyReg.test(val)) {
            $(input).val("");
            layer.msg("请输入正确的重量！", {icon: 5, time: 1000});
            return;
        }
    }
    var inputs = $("input[tdName='" + tdName + "']");
    inputs.each(function (index, tdInput) {
        $(tdInput).val(val);
    })
    showBatch(num, false);
}
//批量修改按钮显示隐藏（th）
function showBatch(name, isShow) {
    var tdName = "#editTd" + name;
    var inputName = "#editTd" + name + "Input";
    name = "#edit" + name;
    if (isShow) {
        $(name).hide();
        $(tdName).show();
        $(inputName).focus();
    } else {
        $(name).show();
        $(tdName).hide();
    }
}
function toThousands(num) {
    //fixme 小数点和这玩意冲突，解决之前不要千位逗号吧
    // return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
}
function OnInput(event) {
    var input = event.target;
    var val = $(input).val();
    var c = event.data;
    var reg = new RegExp("^[0-9]*$");
    val = val.replace(/,/g, "");
    if (!reg.test(c) && c !== ".") {
        val = parseFloat(val)
    }
    if (isNaN(val)) {
        val = "";
    }
    $(input).val(val);
}
function OnPropChanged(event) {
    var input = event.target;
    var val = $(input).val();
    var c = event.data;
    var reg = new RegExp("^[0-9]*$");
    val = val.replace(/,/g, "");
    if (!reg.test(c) && c !== ".") {
        val = parseFloat(val)
    }
    if (isNaN(val)) {
        val = "";
    }
    $(input).val(val);
}
function changePrice(input) {
    var val = $(input).val();
    if (!moneyReg.test(val)) {
        $(input).val("");
        layer.msg("请输入正确的金额！", {icon: 5, time: 1000});
    }
}
function changeInventory(input) {
    var val = $(input).val();
    if (!NonNegativeInteger.test(val)) {
        $(input).val("");
        layer.msg("请输入正确的库存！", {icon: 5, time: 1000});
    }
}
function changeWeight(input) {
    var val = $(input).val();
    if (!NonNegativeInteger.test(val)) {
        $(input).val("");
        layer.msg("请输入正确的数量！", {icon: 5, time: 1000});
    }
}
//发布商品页面
function doLast() {
    console.log({
        skus: skus,
        product: product,
        attributeImage: attributeImage,
        attributes: attributes,
        hasAttribute: hasAttributeFlag
    });
    $("#skuDiv").hide();
    $("#_form").show();
    $step.toStep(3);
    showLastTable();
}
function showLastTable() {
    var productTable = ' <div class="div-info-title"> <p>商品信息</p> </div>' +
        '<div>' +
        '<table class="layui-table">' +
        '<tbody id="">' +
        '<tr><td>商品名称</td><td>' + product.name + '</td></tr>' +
        '<tr><td>商品品牌</td><td>' + $("select[name='brandId']").find("option:selected").html() + '</td></tr>' +
        '<tr><td>商品分类</td><td>' + productCategoryName + '</td></tr>' +
        '<tr><td>商品参数</td><td>';
    $(product.param).each(function (index, para) {
        productTable += '<p>' + para.paramName + ': ' + para.value + '</p>';
    });
    productTable += '</td></tr>' +
        '</tbody>' +
        '</table>' +
        '</div>';
    var skuTable = ' <div class="div-info-title"> <p>sku信息</p> </div>' +
        '<div>' +
        '<table class="layui-table">' +
        '<thead><tr>' +
        '<th>名称</th>' +
        '<th>规格</th>' +
        '<th>售价</th>' +
        '<th>市场价</th>' +
        '<th>成本价</th>' +
        '<th>库存</th>' +
        '<th>重量</th>' +
        '</tr></thead>' +
        '<tbody id="">';
    $(skus).each(function (index, sku) {
        skuTable += '<tr>' + '<td>' + sku.name + '</td><td>';
        $(sku.attribute).each(function (aIndex, attr) {
            skuTable += '<p>' + attr.attributeKey + ': ' + attr.attributeValue + '</p>';
        });
        skuTable += '</td><td>' + sku.price + '</td>' +
            '<td>' + sku.marketPrice + '</td>' +
            '<td>' + sku.costPrice + '</td>' +
            '<td>' + sku.inventory + '</td>' +
            '<td>' + sku.weight + '</td>' +
            '</tr>';
    });
    skuTable += '</tbody>' +
        '</table>' +
        '</div>';
    $("#productLastInfo").empty();
    $("#productLastInfo").append(productTable);
    $("#skuLastInfo").empty();
    $("#skuLastInfo").append(skuTable);
}
function returnSku() {
    $("#skuDiv").show();
    $("#_form").hide();
    $step.toStep(2);
}
//鼠标移入图片事件
function deleteImg(icon) {
    $(icon).next().attr("src", basePath + "/resources/manage/image/noImg.png")
    $(icon).nextAll("input[name='image']").val("");
    $(icon).css("visibility", "hidden");
}
//todo 规格修改后的顺序问题！！！！！！！！！！！！！！！！！！！！！！！
function submitAll(marketable) {
    product.marketable = marketable;
    var data = JSON.stringify({
        skus: skus,
        product: product,
        // attributeImage: attributeImage,
        attributes: attributes,
        hasAttribute: hasAttributeFlag
    });
    if (!subFlag) {
        subFlag = true;
        $.ajax({
            type: 'post',
            url: subUrl,
            data: data,
            contentType: "application/json;charset=utf-8",
            success: function (res) {
                console.log(res);
                if (res.code != 1) {
                    subFlag = false;
                    if(res.data.length > 0){
                        layer.msg(res.data, {icon: 5});
                    }else{
                        layer.msg(res.message, {icon: 5});
                    }
                } else {
                    layer.msg("添加商品成功", {icon: 1, time: 1000}, function () {
                        parent.layer.close(index);
                        parent.$table.bootstrapTable('refresh');
                    });
                }
            },
            error: function (res) {
                subFlag = false;
                layer.msg("操作异常", {icon: 5});
            }
        });
    }
}
function submitEditAll(marketable) {
    product.marketable = marketable;
    product.id = productId;
    var data = JSON.stringify({
        skus: skus,
        product: product,
        attributes: attributes,
        hasAttribute: hasAttributeFlag
    });
    console.log({
        skus: skus,
        product: product,
        attributes: attributes,
        hasAttribute: hasAttributeFlag
    });
    if (!subFlag) {
        subFlag = true;
        $.ajax({
            type: 'post',
            url: updateUrl,
            data: data,
            contentType: "application/json;charset=utf-8",
            success: function (res) {
                if (res.code != 1) {
                    subFlag = false;
                    if(res.data.length > 0){
                        layer.msg(res.data, {icon: 5});
                    }else{
                        layer.msg(res.message, {icon: 5});
                    }
                } else {
                    layer.msg("修改商品成功", {icon: 1, time: 1000}, function () {
                        parent.layer.close(index);
                        parent.$table.bootstrapTable('refresh');
                    });
                }
            },
            error: function (res) {
                subFlag = false;
                layer.msg("操作异常", {icon: 5});
            }
        });
    }
}